capture program drop hlmimport
program define hlmimport, eclass
ereturn clear

version 8.2
syntax varlist, STore(string)
*must enter all variables in order, starting with a constant and including variables representing 
*crosslevel interactions after the individual-level component of the interaction
*store is [null|us|usr|pa|par|eml|l]

****Import the estimates of gammas and their VC matrices from HLM output
*******[from hlmrun 2.0 by Sean F. Reardon (Dec. 2005)] 
loc nvars: word count `varlist'
loc matlines=int(`=`nvars'+59'/60)
foreach f in /*null r us usr pa par eml l*/ `store' {
	if "`f'" == "null" loc f ""
	capture confirm file "gamvc`f'.dat"
	if _rc == 0 {
		tempname bvc b_`f' V_`f'
		file open `bvc' using "gamvc`f'.dat", read
		loc gammas ""
		loc l = 1
		while `l' <= `matlines' {
			file read `bvc' line
			loc gammas "`gammas' `line'"
			loc l = `l' + 1
		}
		loc vcmat ""
		loc r = 1
		while `r' <= `nvars' {
		loc l = 1
			while `l' <= `matlines' {
				file read `bvc' line
				loc vcmat "`vcmat' `line'"
				loc l = `l' + 1
			}
			if `r' < `nvars' loc vcmat "`vcmat' \"
			loc r = `r' + 1
		}
		file close `bvc'
		if "`f'" == "" loc f "lin"
		if "`f'" == "l" loc f "l6"
		matrix input b_`f' = (`gammas')
		matrix input V_`f' = (`vcmat')
		matrix rownames b_`f' = "y1"
		matrix colnames b_`f' = `varlist'
		matrix rownames V_`f' = `varlist'
		matrix colnames V_`f' = `varlist'
		matrix se_`f'=vecdiag(cholesky(diag(vecdiag(V_`f'))))
	}
}

if "`store'" == "null" loc store "lin"
capture confirm matrix b_`store'
if _rc == 0 {
	ereturn post b_`store' V_`store', depname(`out')
	matrix b_`store' = e(b)
	matrix V_`store' = e(V)
	loc disp "y"
}
else {
	di in re ///
	`"note: requested results ("`store'") not produced, e(V) and e(b) not stored"'
	loc disp "n"
}
foreach f in /*lin r us usr pa par eml l6*/ `store' {
	capture confirm matrix b_`f'
	if _rc == 0 {
		if "`f'" != "r" & "`f'" != "usr" & "`f'" != "par" ///
			ereturn matrix b_`f' = b_`f'
		else matrix drop b_`f'
		ereturn matrix V_`f' = V_`f'
		ereturn matrix se_`f' = se_`f'
	}
}

end
